﻿using Faser_VoteSys.Common;
using Faser_VoteSys.Models.Database;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System.Runtime.InteropServices;

namespace Faser_VoteSys.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class VoteController : Controller
    {
        private readonly Faser_VoteSysContext _db;
        private readonly Services.IJWTService _jwtService;

        public VoteController(Faser_VoteSysContext db, Services.IJWTService jwtService)
        {
            _db = db;
            _jwtService = jwtService;
        }

        // 投票
        [Authorize]
        [HttpPost("{ParticipationID}")]
        public ObjectResult Cast(int ParticipationID)
        {
            var userId = _jwtService.GetUserId(HttpContext);

            using var transaction = _db.Database.BeginTransaction();

            // 检查投票目标是否存在
            var votingTarget = _db.Participations.FirstOrDefault(p => p.ParticipationId == ParticipationID);
            if (votingTarget == null)
            {
                return ApiError.VOTE_NOT_FOUND_TARGET;
            }

            votingTarget.VoteCount++;

            var voteRet = _db.SaveChanges();

            if (voteRet == 0)
            {
                return ApiError.DB_NOT_CHANGE;
            }

            // 检查用户该日投票是否已上限
            var userData = _db.Users.FirstOrDefault(u => u.UserId == userId);
            var userVoteCount = userData.LastVoteCount;
            var lastVoteDate = userData.LastVoteDate;
            if (lastVoteDate.Date != System.DateTime.Now.Date)
            {
                userData.LastVoteDate = System.DateTime.Now.Date;
                userData.LastVoteCount = 0;
            }

            if (userVoteCount >= 5)
            {
                return ApiError.VOTE_COUNT_LIMIT;
            }

            userData.LastVoteCount++;

            var userRet = _db.SaveChanges();

            if (userRet == 0)
            {
                return ApiError.DB_NOT_CHANGE;
            }

            transaction.Commit();
            return Ok("");
        }
    }
}
